# -*- coding: utf-8 -*-
#
# Copyright (C) 2008, Patik Geliştiricileri
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#

import os
import sys

from PyQt4 import QtCore, QtGui
from PyQt4.QtNetwork import QHttp
from PyKDE4.kdecore import KAboutData, KCmdLineArgs, KGlobal
from PyKDE4.kdeui import KApplication, KAboutApplicationDialog, KSystemTrayIcon

from ui.ui_patik import Ui_patikWindow
from patikgloballeri import *

import re

class patikWindow(QtGui.QMainWindow, Ui_patikWindow):
    def __init__(self):
	QtGui.QMainWindow.__init__(self)
	self.setupUi(self)

	self.connect(self.actionHakkinda, QtCore.SIGNAL("triggered(bool)"), self.hakkinda)
	self.connect(self.araButton, QtCore.SIGNAL("clicked(bool)"), self.ara)	

    def ara(self):
	kelime = unicode(self.kelimeEdit.text())
	sonuclar = unicode(self.kelimeAl(kelime))

    def hakkinda(self):
	KAboutApplicationDialog(aboutData, self).show()

    def kelimeAl(self, kelime):
	global sozluk

	self.statusbar.showMessage(u"Kelime alınıyor...")

	sozluk = QHttp("www.seslisozluk.com")
	QtCore.QObject.connect(sozluk, QtCore.SIGNAL("done(bool)"), self.kelimeAl_)
	sozluk.get("/?word=%s" % kelime)


    def kelimeAl_(self):
	sozluk_ = str(sozluk.readAll())

	sonuclar_ = re.findall("""<td class=.m.>(.*)</td>""", sozluk_)
	sonuclar = []
	for i in range(len(sonuclar_)):
	    a = "<b>%s</b>. %s" % (str(i + 1), sonuclar_[i])
	    b = re.findall("(<.*?>)", a)
	    for i in b:
		a = a.replace(i, "")
	    sonuclar.append(a.replace("&nbsp;", ""))

	self.sonucAlani.setPlainText(unicode("\n".join(sonuclar), "utf-8"))
	self.statusbar.showMessage(u"Kelime alındı...")

aboutData = KAboutData(uygIsmi, katolog, uygAdi, versiyon, aciklama, lisans, telif, text, webSayfasi, bugEmail)

KCmdLineArgs.init(sys.argv, aboutData)
app = KApplication()
app.setQuitOnLastWindowClosed(False)
mw = patikWindow()
mw.show()

aboutData.setProgramIconName("icons/patik.png")
aboutData.addAuthor(ki18n("Oğuzhan Eroğlu"), ki18n("Kurucu ve geliştirici"), "oguzhan@oguzhaneroglu.com")
aboutData.addAuthor(ki18n("Cihan Okyay"), ki18n("Kurucu ve geliştirici"), "okyaycihan@gmail.com")

def goster(event):
    if event == QtGui.QSystemTrayIcon.Trigger:
	if not mw.isVisible():
	    mw.show()
	else:
	    mw.hide()
    

# trayicon oluşturuluyor...
from ikon import *
tray = KSystemTrayIcon(QtGui.QIcon("icons/patik.png"))
tray.show()

QtCore.QObject.connect(tray, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), goster)

app.exec_()